package com.wzw.springboot.principle.use.websock.second;

import com.wzw.springboot.principle.use.security.infrastructure.model.SecurityUser;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Map;

/**
 * Spring方式  文本类型的连接处理 握手成功后的基础上建立 socket 的连接
 *
 * @author Wangzhiwen
 */
@Component
@SuppressWarnings("NullableProblems")
public class PrincipleWebSocketHandler extends TextWebSocketHandler {

    /**
     * 连接成功时
     *
     * @param session 会话
     * @throws Exception 异常
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String sessionId = session.getId();
        Map<String, Object> attributes = session.getAttributes();
        SecurityUser securityUser = (SecurityUser) attributes.get(SecurityUser.class.getSimpleName());
        WebSocketSessionManager.addSession(session);
        WebSocketSessionManager.sendMessage(securityUser.getId(), new TextMessage("连接成功!!!"));
    }

    /**
     * 接收客户端消息
     *
     * @param session 会话
     * @param message 文本消息
     * @throws Exception 异常
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String sessionId = session.getId();
        byte[] bytes = message.asBytes();
        String payload = message.getPayload();
        System.out.println(payload);
    }

    /**
     * 处理异常
     *
     * @param session   会话
     * @param exception 异常
     * @throws Exception 异常
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
    }

    /**
     * 连接关闭时
     *
     * @param session 会话
     * @param status  关闭状态
     * @throws Exception 异常
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        if (session.isOpen()) {
            WebSocketSessionManager.removeSession(session);
            session.close(status);
        }
    }
}
